package com.chen.controller;

import com.chen.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

@RequestMapping("/common")
@RestController
public class CommonController {
    @Value("${reggie.upload-path}")
    private String uploadPath;

    /**
     * 文件上传
     * @param file 接收图片的类
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws Exception {
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //截取后缀
        String subFilename = originalFilename.substring(originalFilename.lastIndexOf("."));
        //和uuid拼接获得文件名
        String FileName = UUID.randomUUID().toString() + subFilename;

        File fileDri = new File(uploadPath);
        if (!fileDri.exists()) {
            //判断文件夹是否存在  不存在就创建
            fileDri.mkdirs();
        }

        String path = uploadPath + FileName;
        file.transferTo(new File(path));
        return R.success(FileName);
    }

    /**
     * 文件下载
     * @param name 图片名字
     * @param resp 响应
     * @throws Exception
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse resp) throws Exception {
        //根据文件名 创建字节输入流
        FileInputStream is = new FileInputStream(uploadPath + name);
        //获取字节输出流
        ServletOutputStream os = resp.getOutputStream();

        byte[] bytes = new byte[8192];
        int len = -1;
        while ((len = is.read(bytes)) != -1){
            os.write(bytes,0,len);
        }
        is.close();
        os.close();
    }
}
